package me.aip.mov.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.aip.mov.entity.ChatMsg;
import me.aip.mov.entity.UserInfo;
import me.aip.mov.entity.Vod;
import me.aip.mov.mapper.ChatMsgMapper;
import me.aip.mov.mapper.UserInfoMapper;
import me.aip.mov.service.IChatMsgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aip9105
 * @since 2022-02-12
 */
@Service("chatMsg")
public class ChatMsgServiceImpl extends ServiceImpl<ChatMsgMapper, ChatMsg> implements IChatMsgService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public Page<ChatMsg> findChatMsgRecord(Page page, ChatMsg msg) {
        LambdaQueryWrapper<ChatMsg> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.and(wq -> {
                wq.and(wq0 -> {
                    wq0.eq(ChatMsg::getFromUserid,msg.getFromUserid());
                    wq0.eq(ChatMsg::getToUserid,msg.getToUserid());
                });
                wq.or(wq1 ->{
                    wq1.eq(ChatMsg::getToUserid,msg.getFromUserid());
                    wq1.eq(ChatMsg::getFromUserid,msg.getToUserid());
                });
        });
        queryWrapper.orderByDesc(ChatMsg::getTime);
        return this.baseMapper.selectPage(page,queryWrapper);
    }

    @Override
    public Page<ChatMsg> findChatUserMagList(Page page, String userId) {
        Page<ChatMsg> pageList = this.baseMapper.findChatUserMagList(page,userId);
        for (ChatMsg chatMsg : pageList.getRecords()) {
            UserInfo userInfo = userInfoMapper.selectById(chatMsg.getFromUserid());
            chatMsg.setAvatar(userInfo.getAvatar());
            chatMsg.setNickName(userInfo.getNickName());
        }
        return page;
    }

    @Override
    public void updateUnread(String userId, String toUserId) {
        LambdaQueryWrapper<ChatMsg> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMsg::getFromUserid,toUserId);
        queryWrapper.eq(ChatMsg::getToUserid,userId);
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setUnread(1);
        this.baseMapper.update(chatMsg,queryWrapper);
    }

    @Override
    public Integer getUnReadCount(String userId) {
        LambdaQueryWrapper<ChatMsg> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMsg::getToUserid,userId);
        queryWrapper.eq(ChatMsg::getUnread,0);
        return this.baseMapper.selectCount(queryWrapper);
    }
}
